<template>
    <div>
        <Edit :is-detail="type === 'detail'" :ruleForm="ruleForm" ref="editForm" type="17" />
        <Page dir-name="/goods" :type="type" ref="page" :content="ruleForm.content" />
        <div class="submitBtn" >
          <el-button v-if="type !== 'detail'" class="mt10" type="primary" @click="onSubmit">保 存</el-button>
        </div>
    </div>
</template>

<script>
import Edit from '@/views/components/edit.vue'
import { getNewsDetail, addNew, editNew } from '@/api/news'
import Page from '@/views/components/page.vue'
export default {
    name: 'AddDownload',
    components: { Edit, Page },
    data() {
        return {
            ruleForm: {},
            type: '',
            id: null
        }
    },
    async created() {
        if (this.$route.query.id) {
            this.id = this.$route.query.id
            this.type = this.$route.query.type || 'add'
            let res = await getNewsDetail({ id: this.$route.query.id })
            this.ruleForm = res.data
            this.ruleForm.content = JSON.parse(this.ruleForm.content)
        }
    },
    methods: {
        async onSubmit() {
            let form = await this.$refs.editForm.validate()
            let content = await this.$refs.page.getContainer()
            let formData = new FormData()
            formData.append('tpl_id', 1)
            formData.append('title', form.title)
            formData.append('subtitle', form.subtitle)
            formData.append('category_id', form.category_id)
            formData.append('content', JSON.stringify(content || ''))
            this.id !== null && formData.append('id', this.id)
            let fetchApi = this.id !== null ? editNew : addNew
            await fetchApi(formData)
            this.$message({
                type: 'success',
                message: '成功'
            })
            this.id === null && this.$router.push('/news')
        }
    }
}
</script>
<style >
.submitBtn{
  text-align: center;
  border-top: 1px solid #eee;
  width: 96%;
  margin: 40px auto;
}
.submitBtn button{
  width: 200px;
}
</style>